"""
商品扫描业务处理模块
"""
import threading
import queue
from concurrent.futures import ThreadPoolExecutor
from typing import List, Dict, Any
import time
import os
import psutil
import json
from reqapi.get_commodity_list import GetCommodityListApi
from com.db.order_record_manager import OrderRecordManager
from com.db.scan_record_manager import ScanRecordManager
from com.scan_account_pool import ScanAccountPool
from biz.purchase_commodity import PurchaseCommodity
from PyQt6.QtCore import QObject, pyqtSignal, Qt
from com.utils.logger import get_logger,MODULE_SCAN

class CommodityScanner(QObject):
    # 日志信号
    log_signal = pyqtSignal(str)
    
    # 类级别的缓存，记录正在处理的商品
    _processing_items = set()  # 存储正在处理的商品ID
    _cache_lock = threading.Lock()  # 用于保护缓存访问的线程锁
    
    def __init__(self, order_account=None, task=None, script=None):
        """
        初始化商品扫描器
        
        Args:
            order_account: 下单账号信息
            task: 任务信息
            script: 脚本信息
        """
        print("=== 开始初始化 CommodityScanner ===")
        try:
            if not isinstance(task, (dict, type(None))):
                print("错误: task 不是字典类型")
                raise ValueError("task 必须是字典类型")
                
            # 确保在主线程中初始化 QObject
            if threading.current_thread() is not threading.main_thread():
                print("错误: 不在主线程中初始化")
                raise RuntimeError("CommodityScanner must be initialized in the main thread")
            
            print("初始化 QObject 父类")
            try:
                super().__init__()
                print("QObject 父类初始化成功")
            except Exception as e:
                import traceback
                print(f"QObject 父类初始化失败: {str(e)}\n{traceback.format_exc()}")
                raise
            
            print("初始化 ScanAccountPool")
            try:
                self.account_pool = ScanAccountPool()
                print("ScanAccountPool 初始化成功")
            except Exception as e:
                import traceback
                print(f"ScanAccountPool 初始化失败: {str(e)}\n{traceback.format_exc()}")
                self.account_pool = None
                print("设置 account_pool 为 None")
            
            print("初始化基本属性")
            self.running = True
            self.order_account = order_account
            self.task = task
            self.script = script
            self._stop_event = threading.Event()
            print("初始化 ScanRecordManager")
            try:
                self.scan_record_manager = ScanRecordManager()
                print("ScanRecordManager 初始化成功")
            except Exception as e:
                import traceback
                print(f"ScanRecordManager 初始化失败: {str(e)}\n{traceback.format_exc()}")
                self.scan_record_manager = None
            
            print("初始化 logger")
            self.logger = get_logger(module=MODULE_SCAN)
            print("logger 初始化成功")
        except Exception as e:
            import traceback
            print(f"CommodityScanner 初始化过程中发生错误: {str(e)}\n{traceback.format_exc()}")
            raise
        
        # 动态调整线程池大小
        self.max_scan_workers = self._calculate_scan_workers()
        self.max_purchase_workers = min(3, max(1, self.max_scan_workers // 3))  # 购买线程池为扫描线程池的1/3
        
        self.executor = ThreadPoolExecutor(max_workers=self.max_scan_workers)  # 扫描线程池
        self.purchase_executor = ThreadPoolExecutor(max_workers=self.max_purchase_workers)  # 购买线程池
        
    def log(self, message: str):
        """发送日志消息"""
        try:
            self.log_signal.emit(message)
            self.logger.info(message)
        except:
            self.logger.info(message)
            
    def __del__(self):
        """析构函数"""
        try:
            self.executor.shutdown(wait=True)
            self.purchase_executor.shutdown(wait=True)
        except:
            pass
            
    def _is_processing(self, goods_id: str) -> bool:
        """
        检查商品是否正在处理中
        
        Args:
            goods_id: 商品ID
            
        Returns:
            bool: 如果商品正在处理返回True，否则返回False
        """
        with self._cache_lock:
            return goods_id in self._processing_items
            
    def _add_to_processing(self, goods_id: str) -> None:
        """添加商品到处理中状态"""
        with self._cache_lock:
            self._processing_items.add(goods_id)
            
    def _remove_from_processing(self, goods_id: str) -> None:
        """从处理中状态移除商品"""
        with self._cache_lock:
            self._processing_items.discard(goods_id)
            
    def _calculate_delay(self, next_available_time: float) -> float:
        """
        计算距离下次执行的延迟时间（秒）
        
        Args:
            next_available_time: 下次可用时间戳
            
        Returns:
            float: 需要延迟的秒数，如果已经过了执行时间则返回0
        """
        current_time = time.time()
        delay = next_available_time - current_time
        return max(0, delay)

    def _async_purchase(self, template_id: str, commodity_list: List[Dict],task):
        """
        异步执行购买操作
        
        Args:
            template_id: 商品ID
            commodity_list: 商品列表
        """
        try:
            self.log(f"\n[购买] 开始处理商品 {template_id} 的购买")

            # 确保价格是浮点数
            unit_price = sum(float(item["Price"]) for item in commodity_list) / len(commodity_list)
            # 计算总价
            total_amount = sum(float(item["Price"]) for item in commodity_list)
            self.log(f"[购买] 商品数量: {len(commodity_list)}, 单价: {unit_price:.4f}, 总价: {total_amount:.4f}")
            
            # 构造购买所需的商品列表
            purchase_items = []
            for item in commodity_list:
                purchase_items.append({
                    "commodityId": int(item["Id"]),  # 确保ID是整数
                    "commodityIdPrice": str(float(item["Price"])),  # 确保价格是字符串形式的浮点数
                    "templateId": template_id,
                    "commodity":item
                })
            
            # 创建购买处理实例并执行购买
            purchase = PurchaseCommodity(task=task, script=self.script, order_account=self.order_account)
            result = purchase.process_purchase(template_id, purchase_items, total_amount, unit_price)
            
            self.log(f"[购买结果] 商品 {template_id} 的购买结果: {result}")

            if result["success"]:
                self.log(f"[购买成功] 商品 {template_id} 购买成功")
            else:
                self.log(f"[购买失败] 商品 {template_id} 购买失败: {result.get('message', '未知错误')}")
                
        except Exception as e:
            self.log(f"[购买错误] 处理商品 {template_id} 时发生错误: {str(e)}")
        
    def _schedule_scan(self, task: Dict[str, Any], account: Dict[str, Any], result_queue: queue.Queue):
        """
        调度扫描任务，在next_available_time时执行一次
        
        Args:
            task: 扫描任务信息
            account: 扫货账号信息
            result_queue: 结果队列
        """
        try:
            # 记录线程创建时间
            thread_create_time = time.time()
            wait_start_time = time.time()
            
            # 计算延迟时间
            delay = self._calculate_delay(account['next_available_time'])
            
            if delay > 0:
                self.log(f"【等待扫描】商品 {task.get('task', {}).get('name', '')} ({task['goods_id']}) 将在 {delay:.2f} 秒后扫描")
                
                # 使用Event进行等待，这样可以响应停止信号
                if not self._stop_event.wait(delay):
                    wait_end_time = time.time()
                    # 执行扫描，传入时间信息，线程ID在子线程中获取
                    self._scan_commodity(task, account, result_queue, {
                        'thread_create_time': thread_create_time,
                        'wait_start_time': wait_start_time,
                        'wait_end_time': wait_end_time,
                        'wait_duration': round(wait_end_time - wait_start_time, 2)
                    })
                else:
                    self.log(f"【取消扫描】商品 {task['goods_id']} 的扫描任务被取消")
            else:
                # 直接执行扫描
                wait_end_time = time.time()
                self._scan_commodity(task, account, result_queue, {
                    'thread_create_time': thread_create_time,
                    'wait_start_time': wait_start_time,
                    'wait_end_time': wait_end_time,
                    'wait_duration': 0.00
                })
                
        except Exception as e:
            self.log(f"【调度错误】处理商品 {task['goods_id']} 时发生错误: {str(e)}")
            # 确保从处理中状态移除
            self._remove_from_processing(str(task['goods_id']))
            
    def _scan_commodity(self, task: Dict[str, Any], account: Dict[str, Any], result_queue: queue.Queue, timing_info: Dict[str, Any]):
        """
        使用指定账号扫描商品出售数据
        
        Args:
            task: 扫描任务信息
            account: 扫货账号信息
            result_queue: 结果队列，用于存储扫描结果
            timing_info: 时间信息，包含线程创建和等待时间
        """
        goods_id = str(task['goods_id'])
        goods_name = task.get('task', {}).get('name', '')
        account_info = account['account']  # 移到前面，避免后面重复访问
        scan_start_time = time.time()
        
        # 在子线程中获取真实的线程ID
        thread_id = threading.get_ident()
        
        # 先输出日志，保持原有顺序
        self.log(f"[扫描] 使用账号: 【{account_info['name']}】开始扫描商品 {goods_id}【{goods_name}】")
        
        scan_record = {
            # 基本信息
            'task_id': task['task_id'],
            'script_id': self.script['id'] if self.script else None,
            'goods_id': goods_id,
            'goods_name': task.get('task', {}).get('name', ''),
            'account_id': account_info['id'],
            
            # 时间信息
            'thread_id': thread_id,
            'thread_create_time': timing_info['thread_create_time'],
            'wait_start_time': timing_info['wait_start_time'],
            'wait_end_time': timing_info['wait_end_time'],
            'wait_duration': timing_info['wait_duration'],
            'scan_start_time': scan_start_time,
            
            # 扫描配置
            'price_limit': task['task']['buy_price_limit'],
            'min_paintwear': task.get('filter_conf', {}).get('min_paintwear', '0.15'),
            'max_paintwear': task.get('filter_conf', {}).get('max_paintwear', '0.18')
        }
        
        try:
            # 检查购买数量限制
            order_record_manager = OrderRecordManager()
            active_count = order_record_manager.get_active_purchase_count(str(task['task_id']))
            buy_num_limit = task['task'].get('buy_num_limit', 0)
            
            # 记录可购买数量
            remaining_limit = 0 if buy_num_limit is None else buy_num_limit - active_count
            scan_record['remaining_purchase'] = remaining_limit
            
            if buy_num_limit is None:
                self.log(f"[购买限制] 商品 {goods_id} 未设置购买限制")
            else:
                if remaining_limit <= 0:
                    self.log(f"[购买限制] 商品 {goods_id} 已达到购买限制({buy_num_limit})，进行中/已完成数量：{active_count}")
                    scan_record.update({
                        'scan_status': 'limited',
                        'error_message': f'已达到购买限制({buy_num_limit})'
                    })
                    result_queue.put({
                        'task': task,
                        'account_id': account_info['id'],
                        'success': False,
                        'error': f'已达到购买限制({buy_num_limit})'
                    })
                    return
                
                # self.log(f"[购买限制] 商品 {goods_id} 剩余可购买数量：{remaining_limit}")
        
            api = GetCommodityListApi(
                device_token=account_info.get('device_id', ''),
                device_id=account_info.get('device_id', ''),
                auth_token=account_info.get('uu_token', ''),
                uk=account_info.get('uk', ''),
                user_id=account_info.get('uu_user_id', '')
            )
            
            # 请求商品出售数据
            api_start_time = time.time()
            filter_conf = task.get('filter_conf', {})
            response = api.execute(
                min_abrade = filter_conf.get('min_paintwear', '0'),
                max_abrade = filter_conf.get('max_paintwear', '1'),
                template_id=str(task['goods_id']),
                page_size='10'
            )
            api_end_time = time.time()
            
            # 记录API响应时间
            api_response_time = round(api_end_time - api_start_time, 2)
            scan_record['api_response_time'] = api_response_time
            
            # 检查是否是轮询模式的任务，如果是，立即通知任务已完成
            if task.get('polling_mode', False):
                # 将任务标记为已完成
                # self.log(f"[轮询扫货] 商品 {goods_id} API调用完成，立即返回通知")
                # 将结果放入队列，通知调用者
                result_queue.put({
                    'task': task,
                    'account_id': account_info['id'],
                    'success': True,
                    'api_complete': True,
                    'message': f'API调用完成，继续处理中'
                })
                # 注意：这里不返回，继续执行后续的购买流程
        
            api_fallback_used = False
            if isinstance(response, dict) and (response.get("code") == 84104 or response.get("Code") == 84104):
                self.log(f"[API切换] 商品 {goods_id} 原API返回84104错误，切换到PC端API")
                
                # 导入PC端API和模型
                from reqapi.query_on_sale_commodity_list import QueryOnSaleCommodityListAPI
                from reqapi.models.query_on_sale_commodity_list import QueryOnSaleCommodityListRequest
                
                # 创建PC端API实例，使用固定的UK值
                fixed_uk = "5FDLjNAFdQEqN5frHEmeMoUGuRxmiky5ffdWZzUGugruOCyghLTNDWCoxZl6jE51O"
                pc_api = QueryOnSaleCommodityListAPI(
                    authorization=account_info.get('uu_token', ''),
                    uk=fixed_uk
                )
                
                # 构造请求参数，参考main方法中的调用方式
                request = QueryOnSaleCommodityListRequest(
                    templateId=str(task['goods_id']),
                    minAbrade=filter_conf.get('min_paintwear', '0'),
                    maxAbrade=filter_conf.get('max_paintwear', '1'),
                    pageIndex=1,
                    pageSize=10
                )
                
                # 记录API切换时间
                pc_api_start_time = time.time()
                
                # 发送PC端API请求
                try:
                    pc_response = pc_api.query(request)
                    pc_api_end_time = time.time()
                    api_fallback_used = True
                    
                    # 将PC端API响应转换为与APP端API相同的格式
                    # 注意：确保字段名称和大小写与APP端API完全一致，以便后续购买流程正常处理
                    response = {
                        "Code": pc_response.Code,
                        "Msg": pc_response.Msg,
                        "Data": {
                            "CommodityList": [
                                {
                                    # 购买流程中必须的字段，确保大小写与原API一致
                                    "Id": item.id,  # 用于commodityId
                                    "Price": item.price,  # 用于commodityIdPrice
                                    "TemplateId": item.templateId,  # 用于templateId
                                    
                                    # 购买记录中需要的字段
                                    "CommodityName": item.commodityName,
                                    "CommodityHashName": item.commodityHashName,
                                    "GameId": item.gameId,
                                    "Abrade": item.abrade,
                                    
                                    # 其他必要字段
                                    "Type": item.type,
                                    "UserId": item.userId,
                                    "IconUrl": item.iconUrl,
                                    "IconUrlLarge": item.iconUrlLarge,
                                    "UserNickName": item.userNickName,
                                    "UserAvatar": item.userAvatar,
                                    "CommodityNo": item.commodityNo,
                                    "PublishTime": item.publishTime,
                                    "Mine": item.mine,
                                    "TypeName": item.typeName,
                                    
                                    # 贴纸相关字段
                                    "Stickers": [
                                        {
                                            "id": sticker.id,
                                            "name": sticker.name,
                                            "img": sticker.img,
                                            "wear": sticker.wear,
                                            "slot": sticker.slot
                                        } for sticker in item.stickers
                                    ] if item.stickers else [],
                                    "HaveSticker": item.haveSticker,
                                    "HaveBuZhang": item.haveBuZhang,
                                    "HaveNameTag": item.haveNameTag,
                                    
                                    # 其他可能需要的字段
                                    "CanSold": item.canSold,
                                    "Actions": item.actions,
                                    "PaintSeed": item.paintSeed,
                                    "Remark": item.remark
                                } for item in pc_response.Data
                            ] if pc_response.Data else []
                        },
                        "TotalCount": pc_response.TotalCount
                    }
                    
                    # self.log(f"[API切换] 商品 {goods_id} 成功切换到PC端API，响应码: {pc_response.Code}")
                    
                    # 更新API时间记录
                    api_end_time = pc_api_end_time
                    api_start_time = pc_api_start_time
                    api_response_time = round(api_end_time - api_start_time, 2)
                    scan_record['api_response_time'] = api_response_time
                    
                    # 如果是轮询模式的任务，在API切换完成后也发送通知
                    if task.get('polling_mode', False) and not result_queue.empty():
                        self.log(f"[轮询扫货] 商品 {goods_id} API切换完成，发送额外通知")
                        result_queue.put({
                            'task': task,
                            'account_id': account_info['id'],
                            'success': True,
                            'api_complete': True,
                            'message': f'API切换完成，继续处理中'
                        })
                
                except Exception as e:
                    self.log(f"[API切换失败] 商品 {goods_id} 切换到PC端API时发生错误: {str(e)}")
                    # 保持原始响应不变，继续处理原始错误
            
            # 处理API响应
            if isinstance(response, dict):
                if response.get("Code") == 0 or (api_fallback_used and response.get("Code") == 200):
                    data = response.get("Data", {})
                    commodity_list = data.get("CommodityList", [])  
                    total_count = response.get("TotalCount", 0)  # 获取在售总数
                    # self.log(f"[扫描成功] 商品 {goods_id} 找到 {len(commodity_list)} 个出售项")
                    # self.log(f"[在售数量] 商品 {goods_id} 在售总数: {total_count}")  # 添加日志
                    # print(data)
                    
                    # 提取价格列表
                    try:
                        price_list = [float(item.get('Price', 0)) for item in commodity_list if item.get('Price')]
                        # self.log(f"[价格列表] 商品 {goods_id} 价格列表: {price_list}")
                    except Exception as e:
                        self.log(f"[警告] 提取价格列表时发生错误: {str(e)}")
                        price_list = []
                    
                    # 统计符合购买价格的商品数量
                    buy_price_limit = task['task']['buy_price_limit']
                    valid_commodities = [
                        item for item in commodity_list 
                        if float(item.get('Price', float('inf'))) <= buy_price_limit
                    ]
                    purchase_success_count = len(valid_commodities)
                    # self.log(f"[价格符合] 商品 {goods_id}【{goods_name}】 符合购买价格的数量: {purchase_success_count}")
                    
                    # 更新扫描记录
                    try:
                        scan_record.update({
                            'api_response_code': response.get("Code"),
                            'api_response_time': round(api_end_time - api_start_time, 2),
                            'found_items': len(commodity_list),
                            'min_price': min(price_list) if price_list else None,
                            'max_price': max(price_list) if price_list else None,
                            'avg_price': sum(price_list) / len(price_list) if price_list else None,
                            'selling_count': total_count,
                            'price_list': json.dumps(price_list) if price_list else None,
                            'scan_status': 'success',
                            'error_message': None,
                            'purchase_success_count': purchase_success_count  # 添加扫货成功数量
                        })
                        # self.log(f"[记录更新] 商品 {goods_id} 的扫描记录已更新")
                    except Exception as e:
                        self.log(f"[警告] 更新扫描记录时发生错误: {str(e)}")
                        scan_record.update({
                            'scan_status': 'failed',
                            'error_message': f'更新记录时发生错误: {str(e)}'
                        })
                    
                    # 如果有商品数据，异步调用购买业务
                    if commodity_list and remaining_limit > 0:
                        try:
                            # 筛选满足价格限制的商品
                            buy_price_limit = task['task']['buy_price_limit']
                            valid_commodities = [
                                item for item in commodity_list 
                                if float(item.get('Price', float('inf'))) <= buy_price_limit
                            ]
                            
                            if not valid_commodities:
                                self.log(f"[扫描结果] 商品 {goods_id}【{goods_name}】 没有满足价格限制 {buy_price_limit} 的商品")
                            else:
                                # 限制购买数量
                                valid_commodities = valid_commodities[:remaining_limit]
                                self.log(f"[扫描成功] 商品 {goods_id}【{goods_name}】 限制购买数量为 {remaining_limit}, 满足价格限制的可购买数量 {len(valid_commodities)} 个")
                                
                                try:
                                    # 提交异步购买任务
                                    self.purchase_executor.submit(
                                        self._async_purchase,
                                        goods_id,
                                        valid_commodities,
                                        task['task']
                                    )
                                    self.log(f"[扫描成功] 已提交商品 {goods_id}【{goods_name}】 的购买任务")
                                except Exception as e:
                                    self.log(f"[错误] 提交购买任务时发生错误: {str(e)}")
                            
                        except Exception as e:
                            self.log(f"[错误] 处理商品 {goods_id}【{goods_name}】 的购买限制时发生错误: {str(e)}")
                    
                    # 将结果放入队列
                    result_queue.put({
                        'task': task,
                        'account_id': account_info['id'],
                        'success': True,
                        'data': commodity_list,
                        'purchase_initiated': bool(commodity_list and remaining_limit > 0)
                    })
                else:
                    self.log(f"[扫描失败] 商品 {goods_id} 【{goods_name}】扫描失败: {response}")
                    scan_record.update({
                        'scan_status': 'failed',
                        'error_message': str(response),
                        'api_response_code': response.get("Code"),
                        'api_response_time': round(api_end_time - api_start_time, 2)
                    })
                    result_queue.put({
                        'task': task,
                        'account_id': account_info['id'],
                        'success': False,
                        'error': response
                    })
                    
        except Exception as e:
            scan_record.update({
                'scan_status': 'failed',
                'error_message': str(e)
            })
            self.log(f"[扫描错误] 扫描商品 {goods_id}【{goods_name}】 时发生错误: {str(e)}")
            result_queue.put({
                'task': task,
                'account_id': account_info['id'],
                'success': False,
                'error': str(e)
            })
        finally:
            # 记录结束时间
            scan_end_time = time.time()
            thread_end_time = time.time()
            scan_record.update({
                'scan_end_time': scan_end_time,
                'scan_duration': round(scan_end_time - scan_start_time, 2),
                'thread_end_time': thread_end_time,
                'total_duration': round(thread_end_time - timing_info['thread_create_time'], 2)
            })
            
            # 保存扫描记录到数据库
            try:
                self.scan_record_manager.add_scan_record(scan_record)
            except Exception as e:
                self.log(f"[警告] 保存扫描记录时发生错误: {str(e)}")
            
            # 无论成功失败，都从处理中状态移除
            self._remove_from_processing(goods_id)
            
    def start_scan_tasks(self, tasks: List[Dict[str, Any]]):
        """
        开始扫描多个商品的任务
        
        Args:
            tasks: 要扫描的任务列表，每个任务包含商品ID等信息
        """
        if not tasks:
            self.log("【无任务】没有需要扫描的任务")
            return
            
        # 过滤出未处理的商品
        unprocessed_tasks = []
        for task in tasks:
            goods_id = str(task['goods_id'])
            if not self._is_processing(goods_id):
                self._add_to_processing(goods_id)  # 立即标记为处理中
                unprocessed_tasks.append(task)
        
        if not unprocessed_tasks:
            # self.log("【所有处理中】所有商品都在处理中")
            return
            
        # 获取扫货账号
        needed_accounts = len(unprocessed_tasks)
        accounts = self.account_pool.get_accounts_with_intervals(needed_accounts)
        
        # 创建结果队列
        result_queue = queue.Queue()
        
        # 将任务和账号组合，并按照账号的next_available_time排序
        task_account_pairs = list(zip(unprocessed_tasks, accounts))
        task_account_pairs.sort(key=lambda x: x[1]['next_available_time'])
        
        # 提交扫描任务
        futures = []
        for task, account in task_account_pairs:
            future = self.executor.submit(self._schedule_scan, task, account, result_queue)
            futures.append(future)
            
        # 返回任务列表，让调用者可以选择是否等待结果
        return futures, result_queue

    def stop(self):
        """停止扫描器"""
        self.running = False
        self.executor.shutdown(wait=True)
        self.purchase_executor.shutdown(wait=True)

    def _calculate_scan_workers(self):
        """
        计算合适的扫描线程池大小
        
        根据系统CPU核心数和内存情况动态计算合适的线程数
        """
        try:
            # 获取CPU核心数
            cpu_count = os.cpu_count() or 4
            
            # 获取系统内存信息
            memory = psutil.virtual_memory()
            total_gb = memory.total / (1024 * 1024 * 1024)  # 转换为GB
            available_gb = memory.available / (1024 * 1024 * 1024)  # 转换为GB
            
            # 基于可用资源计算合适的线程数
            # 1. CPU因子：使用CPU核心数的2倍作为基准
            cpu_factor = cpu_count * 2
            
            # 2. 内存因子：每个线程预估使用200MB内存
            memory_factor = int(available_gb * 5)  # 每GB可用内存分配5个线程
            
            # 3. 综合考虑各种因素，取较小值
            workers = min(
                cpu_factor,
                memory_factor,
                20  # 设置最大上限为20个线程
            )
            
            # 确保至少有2个线程，最多20个线程
            workers = max(2, min(workers, 20))
            
            # 使用print而不是self.log，因为此时logger可能还未初始化
            print(f"【线程池配置】CPU核心数: {cpu_count}, 可用内存: {available_gb:.1f}GB, 分配线程数: {workers}")
            
            return workers
            
        except Exception as e:
            # 使用print而不是self.log，因为此时logger可能还未初始化
            print(f"计算线程池大小时出错: {str(e)}, 使用默认值8")
            return 8

if __name__ == "__main__":
    import sys
    import time
    import queue
    import random
    import threading
    from PyQt6.QtWidgets import QApplication
    
    # 创建QApplication实例
    app = QApplication(sys.argv)
    
    # 购买账号信息
    order_account = {
        "id": "5",
        "name":"孙菲菲",
        "uu_user_id":"9534592",
        "device_token": "Z7LeH7vdDYcDAIYI3/TVXfAH",
        "device_id": "Z7LeH7vdDYcDAIYI3/TVXfAH",
        "uu_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI3MDU0NzI4MDkyNGI0NjYyYmQ0ZGEzMzQxYWExZTM5OSIsIm5hbWVpZCI6Ijk1MzQ1OTIiLCJJZCI6Ijk1MzQ1OTIiLCJ1bmlxdWVfbmFtZSI6IuWFqOWkqTgxNTkiLCJOYW1lIjoi5YWo5aSpODE1OSIsInZlcnNpb24iOiJjdVUiLCJuYmYiOjE3NDE0MjAwMDcsImV4cCI6MTc0NDU4MDgwNywiaXNzIjoieW91cGluODk4LmNvbSIsImRldmljZUlkIjoiWjdMZUg3dmREWWNEQUlZSTMvVFZYZkFIIiwiYXVkIjoidXNlciJ9.PMXsEg2PqnAroFikZKKUPdB1_I5h6hjgL1JzPHSUYso",
        "uk": "5FDFSRFUD0wsn4vgzgeZpQIxPQzgCtMd3SfawJ2FStxg6MCO4d1esVBdyWoCfkr1N"
    }

    scan_account = {
        "id": "5",
        "name":"孙菲菲",
        "uu_user_id":"9534556",
        "device_token": "Z86b6xe05zIDAPwIHgQPIgOa",
        "device_id": "Z86b6xe05zIDAPwIHgQPIgOa",
        "uu_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI3ZmYwYjc4NzA0NDI0ODE3OThkNzFhMDg3NTE1YzRhOSIsIm5hbWVpZCI6Ijk1MzQ1NTYiLCJJZCI6Ijk1MzQ1NTYiLCJ1bmlxdWVfbmFtZSI6IumAn-WPkTEzMSIsIk5hbWUiOiLpgJ_lj5ExMzEiLCJ2ZXJzaW9uIjoiTEd5IiwibmJmIjoxNzQxNTkyMDc0LCJleHAiOjE3NDI0NTYwNzQsImlzcyI6InlvdXBpbjg5OC5jb20iLCJkZXZpY2VJZCI6IjMxMDZiNTU1LTM3MjctNDExZi05ZjA0LTU1NjlkNzZkMmYzYyIsImF1ZCI6InVzZXIifQ.onwhKqao2eZn7OuqcCUu5SfSx0tg4pOs5kxrTBHCoyw",
        "uk": "5FEbJmzOPAQDW6n67AacoxQRCkZI6uDlfzStZqvGQpefetuvyQ3icAydrinVR651O"
    }

    # 任务和脚本信息
    task = {
        "id": 1,
        "name": "测试任务"
    }
    script = {
        "id": 1,
        "name": "测试脚本"
    }

    # 创建扫描器实例
    scanner = CommodityScanner(order_account, task=task, script=script)
    scanner.logger.info("\n[初始化] 创建扫描器实例完成")
    
    # 定义单个商品的扫描任务
    task = {
        "goods_id": "100606",  # 这里替换为实际的商品ID
        "task_id": 1,  # 添加任务ID
        "task": {
            "id": 1,
            "name": "测试任务",
            "buy_price_limit": 0.7,  # 设置购买价格上限
            "buy_num_limit": 2  # 设置购买数量限制
        },
        "filter_conf": {
            "min_paintwear": "0.07",  # 最小磨损度
            "max_paintwear": "0.08"   # 最大磨损度
        },
        "account": order_account  # 添加扫货账号信息
    }
    
    scanner.logger.info(f"\n[任务配置]")
    scanner.logger.info(f"商品ID: {task['goods_id']}")
    scanner.logger.info(f"价格上限: {task['task']['buy_price_limit']}")
    scanner.logger.info(f"最小磨损: {task['filter_conf']['min_paintwear']}")
    scanner.logger.info(f"最大磨损: {task['filter_conf']['max_paintwear']}")
    
    # 开始扫描任务
    scanner.logger.info("\n[开始任务] 启动扫描任务")
    
    # 创建账号结构
    account = {
        'account': order_account,
        'next_available_time': time.time()
    }
    
    # 手动调用_schedule_scan方法，而不是使用start_scan_tasks
    result_queue = queue.Queue()
    future = scanner.executor.submit(scanner._schedule_scan, task, account, result_queue)
    futures = [future]
    
    # 等待扫描结果
    scanner.logger.info("\n[等待结果] 等待扫描任务完成...")
    for future in futures:
        future.result()  # 等待任务完成
        
    # 获取扫描结果
    scanner.logger.info("\n[处理结果]")
    while not result_queue.empty():
        result = result_queue.get()
        if result['success']:
            scanner.logger.info(f"扫描成功，找到 {len(result['data'])} 个商品")
            if result['purchase_initiated']:
                scanner.logger.info("已启动购买流程")
        else:
            scanner.logger.info(f"扫描失败: {result.get('error', '未知错误')}")
    
    # 停止扫描器
    scanner.logger.info("\n[清理] 停止扫描器")
    scanner.stop()
    
    scanner.logger.info("\n=== 测试流程结束 ===\n")
    
    # 退出应用
    sys.exit(app.exec())
